package com.jiyun.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiyun.om.entity.ShippingMethods;
import com.jiyun.om.entity.Waybill;
import com.jiyun.om.entity.WaybillExcel;
import com.jiyun.result.Result;
import com.jiyun.service.IShippingMethodsService;
import com.jiyun.service.IWaybillService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 运单表 前端控制器
 * </p>
 *
 * @author zhx
 * @since 2025-02-12
 */
@RestController
@RequestMapping("/waybill")
@Tag(name = "运单管理")
public class WaybillController {
    @Autowired
    private IWaybillService waybillService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Operation(summary = "分页查询运单")
    @RequestMapping("/getAll")
    public Page<Waybill> getAll(Integer pageNum, Integer pageSize, @RequestBody Waybill waybill) {
        return waybillService.getAll(pageNum, pageSize, waybill);
    }

    @Operation(summary = "修改运单")
    @RequestMapping("/Update")
    public Result Update(@RequestBody Waybill waybill) {
        // 在修改运单前，将原始数据存储到Redis缓存中
        Waybill originalWaybill = waybillService.getById(waybill.getId());
        if (originalWaybill != null) {
            redisTemplate.opsForValue().set("waybill:" + waybill.getId(), originalWaybill);
        }
        waybillService.updateById(waybill);
        return Result.ok();
    }

    @Operation(summary = "运单详情")
    @RequestMapping("/XiangQing")
    public Waybill XiangQing(@RequestBody Waybill waybill) {
        return waybillService.getById(waybill.getId());
    }

    @Operation(summary = "取消调度")
    @RequestMapping("/toRetern")
    public Result toRetern(@RequestBody Waybill waybill) {
        // 从Redis缓存中获取原始运单数据
        Waybill originalWaybill = (Waybill) redisTemplate.opsForValue().get("waybill:" + waybill.getId());
        // 将原始数据更新回数据库
        if (originalWaybill != null) {
            waybillService.updateById(originalWaybill);
            // 更新成功后，从Redis缓存中删除该数据
            redisTemplate.delete("waybill:" + waybill.getId());
            return Result.ok();
        } else {
            return Result.fail();
        }
    }

    @Operation(summary = "运单下拉框")
    @RequestMapping("/findWaybill")
    public List<Waybill> findWaybill() {
        return waybillService.list();
    }

    @Operation(summary = "导出")
    @RequestMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        List<Waybill> list = waybillService.findAll();
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();
        XSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("运单号");
        row.createCell(1).setCellValue("始发地");
        row.createCell(2).setCellValue("目的地");
        row.createCell(3).setCellValue("运单状态");
        row.createCell(4).setCellValue("计费方式");
        row.createCell(5).setCellValue("运费合计");
        row.createCell(6).setCellValue("计划发车时间");
        row.createCell(7).setCellValue("实际发车时间");
        row.createCell(8).setCellValue("计划到达时间");
        row.createCell(9).setCellValue("实际到达时间");
        row.createCell(10).setCellValue("接单时间");
        row.createCell(11).setCellValue("下单时间");
        row.createCell(12).setCellValue("创建人");
        row.createCell(13).setCellValue("创建时间");
        row.createCell(14).setCellValue("车型");
        row.createCell(15).setCellValue("车长");
        row.createCell(16).setCellValue("车牌号");
        row.createCell(17).setCellValue("手机号码");
        row.createCell(18).setCellValue("司机");
        row.createCell(19).setCellValue("承运商");
        row.createCell(20).setCellValue("运输方式");
        for (int i = 0; i < list.size(); i++) {
            Waybill waybill = list.get(i);
            XSSFRow xssfRow = sheet.createRow(i + 1);
            xssfRow.createCell(0).setCellValue(waybill.getWaybillId());
            xssfRow.createCell(1).setCellValue(waybill.getOrigin());
            xssfRow.createCell(2).setCellValue(waybill.getDestination());
            xssfRow.createCell(3).setCellValue(waybill.getStatus());
            xssfRow.createCell(4).setCellValue(waybill.getBillingMethod());
            xssfRow.createCell(5).setCellValue(waybill.getTotalFreight().doubleValue());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(waybill.getPlannedDepartureTime());
            xssfRow.createCell(6).setCellValue(format);
            String format1 = simpleDateFormat.format(waybill.getActualDepartureTime());
            xssfRow.createCell(8).setCellValue(format1);
            String format2 = simpleDateFormat.format(waybill.getPlannedArrivalTime());
            xssfRow.createCell(7).setCellValue(format2);
            String format3 = simpleDateFormat.format(waybill.getActualArrivalTime());
            xssfRow.createCell(9).setCellValue(format3);
            String format4 = simpleDateFormat.format(waybill.getOrderTime());
            xssfRow.createCell(10).setCellValue(format4);
            String format5 = simpleDateFormat.format(waybill.getPlacementTime());
            xssfRow.createCell(11).setCellValue(format5);
            xssfRow.createCell(12).setCellValue(waybill.getCreator());
            String format6 = simpleDateFormat.format(waybill.getCreationTime());
            xssfRow.createCell(13).setCellValue(format6);
            xssfRow.createCell(14).setCellValue(waybill.getVehicleModel());
            xssfRow.createCell(15).setCellValue(waybill.getVehicleLength());
            xssfRow.createCell(16).setCellValue(waybill.getLicensePlate());
            xssfRow.createCell(17).setCellValue(waybill.getDriverPhone());
            xssfRow.createCell(18).setCellValue(waybill.getDriverName());
            xssfRow.createCell(19).setCellValue(waybill.getCarrier());
            xssfRow.createCell(20).setCellValue(waybill.getTransportMode());
        }
        response.setHeader("Content-Disposition", "attachment;filename=Waybill.xlsx");
        workbook.write(response.getOutputStream());
        workbook.close();
    }
    @Operation(summary = "导入")
    @RequestMapping("/importExcel")
    public void importExcel(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), WaybillExcel.class, new ReadListener<WaybillExcel>() {
            @Override
            public void invoke(WaybillExcel waybillExcel,AnalysisContext analysisContext) {
                try {
                    Waybill waybill = new Waybill();
                    BeanUtils.copyProperties(waybillExcel,waybill);
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date parse = simpleDateFormat.parse(waybillExcel.getPlannedDepartureTime().toString());
                    Date parse1 = simpleDateFormat.parse(waybillExcel.getActualDepartureTime().toString());
                    Date parse2 = simpleDateFormat.parse(waybillExcel.getPlannedArrivalTime().toString());
                    Date parse3 = simpleDateFormat.parse(waybillExcel.getActualArrivalTime().toString());
                    Date parse4 = simpleDateFormat.parse(waybillExcel.getOrderTime().toString());
                    Date parse5 = simpleDateFormat.parse(waybillExcel.getPlacementTime().toString());
                    Date parse6 = simpleDateFormat.parse(waybillExcel.getCreationTime().toString());
                    waybill.setActualDepartureTime(parse1);
                    waybill.setActualArrivalTime(parse3);
                    waybill.setOrderTime(parse4);
                    waybill.setPlannedArrivalTime(parse2);
                    waybill.setPlacementTime(parse5);
                    waybill.setCreationTime(parse6);
                    waybill.setPlannedDepartureTime(parse);
                    waybillService.save(waybill);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                System.out.println("读取完成");
                System.out.println("读取完成");
                System.out.println("读取完成");
            }
        }).sheet().doRead();

    }

}
